Imports System.Threading

Friend Class Consult
    Inherits Threads.BikiThread
    Private m_consultRet As Consult_Args
    Private m_status As String = ""
    Private m_integrated As streamType = streamType.STREAM_INTEGRATED

    Friend Enum ByteRead As Byte
        BY_TRUE = 0
        BY_FALSE = 1
        BY_NODATA = 3
    End Enum

    Friend Enum ConsultBytes As ULong
        CB_RPM_HI = &H0
        CB_RPM_LO = &H1
        CB_AFM_HI = &H4
        CB_AFM_LO = &H5
        CB_TEMP = &H8
        CB_LH_O2 = &H9
        CB_RH_O2 = &HA
        CB_SPEED = &HB
        CB_BVOLT = &HC
        CB_TPS = &HD
        CB_LOAD = &HF
        CB_VETRACE = &H10
        CB_DBR1 = &H13
        CB_INJ_HI = &H14
        CB_INJ_LO = &H15
        CB_IGN = &H16
        CB_AAC = &H17
        CB_DCR1 = &H1E
        CB_DCR2 = &H1F
    End Enum

    Private Const TRIGGER_COUNT As Byte = 20
    Private Const CONSULT_BYTES As Byte = 18
    Private Const AD_INPUTS_CNT As Byte = 3
    Private Const SWITCH_CNT As Byte = 6
    Private Const OUTPUT_CNT As Byte = 5
    Friend Structure _typAdInput
        Dim Raw As UInt16
        Dim Lookup As Single
        Dim Bits As Byte
        Sub Initialise(ByRef _Array As Byte(), ByRef Offset As Integer)
            Raw = System.BitConverter.ToUInt16(_Array, pp(Offset, 2))
            Lookup = System.BitConverter.ToSingle(_Array, pp(Offset, 4))
            Bits = _Array(pp(Offset))
        End Sub
        Sub ToArgs(ByRef Args As Consult_Args, ByVal Num As Byte)
            Args.ADClookup(Num) = Lookup
            Args.setAD(Raw, Num)
        End Sub
    End Structure
    Friend Structure _typSwInput
        Dim value As Byte
        Dim bounce As Byte
        Sub Initialise(ByRef _Array As Byte(), ByRef Offset As Integer)
            value = _Array(pp(Offset))
            bounce = _Array(pp(Offset))
        End Sub
        Sub ToArgs(ByRef Args As Consult_Args, ByVal Num As Byte)
            Args.setSWI(value, Num)
        End Sub
    End Structure
    Friend Structure _typOutput
        Dim OnOff As Byte
        Dim Value As Single
        Sub Initialise(ByRef _Array As Byte(), ByRef Offset As Integer)
            OnOff = _Array(pp(Offset))
            Value = System.BitConverter.ToSingle(_Array, pp(Offset, 4))
        End Sub
        Sub ToArgs(ByRef Args As Consult_Args, ByVal Num As Byte)
            Args.setBKO(Value * 100, Num)
            Args.BKO_OnOff(Num) = OnOff
        End Sub
    End Structure
    Friend Structure _typConsult
        Dim BitSet As UInt32
        Dim Packet() As Byte
        Dim RPM As UInt16
        Dim AFM As UInt16
        Dim TPS As Byte
        Dim MAP As UInt16
        Dim SPEED As Byte
        Dim TEMP As Byte
        Dim LOAD As Byte
        Dim INJ As UInt16
        Dim IGN As Byte
        Dim BVOLTS As Byte
        Sub Initialise(ByRef _Array As Byte(), ByRef Offset As Integer)
            BitSet = System.BitConverter.ToUInt16(_Array, pp(Offset, 4))
            ReDim Packet(CONSULT_BYTES - 1)
            Array.Copy(_Array, pp(Offset, CONSULT_BYTES), Packet, 0, CONSULT_BYTES)
            RPM = System.BitConverter.ToUInt16(_Array, pp(Offset, 2))
            AFM = System.BitConverter.ToUInt16(_Array, pp(Offset, 2))
            TPS = _Array(pp(Offset))
            MAP = System.BitConverter.ToUInt16(_Array, pp(Offset, 2))
            SPEED = _Array(pp(Offset))
            TEMP = _Array(pp(Offset))
            LOAD = _Array(pp(Offset))
            INJ = System.BitConverter.ToUInt16(_Array, pp(Offset, 2))
            IGN = _Array(pp(Offset))
            BVOLTS = _Array(pp(Offset))
        End Sub
        Sub ToArgs(ByRef Args As Consult_Args)
            If BitSet > 0 AndAlso Packet(0) = &HFF AndAlso Packet(1) > 0 Then
                For i As UInt16 = 0 To Packet(1)
                    Select Case decodeConsultBitSet(BitSet, i)
                        Case ConsultBytes.CB_AAC
                            Args.setAac(Packet(i + 2))
                        Case ConsultBytes.CB_AFM_HI
                            Args.setAFM(((Args.getAFM() And &HFF) Or (CUShort(Packet(i + 2)) * &H100)))
                        Case ConsultBytes.CB_AFM_LO
                            Args.setAFM((Args.getAFM() And &HFF00) Or Packet(i + 2))
                        Case ConsultBytes.CB_BVOLT
                            Args.setBVoltage(Packet(i + 2))
                        Case ConsultBytes.CB_DBR1
                            Args.setRegister1(Packet(i + 2))
                        Case ConsultBytes.CB_DCR1
                            Args.setRegister2(Packet(i + 2))
                        Case ConsultBytes.CB_DCR2
                            Args.setRegister3(Packet(i + 2))
                        Case ConsultBytes.CB_IGN
                            Args.setIgnition(Packet(i + 2))
                        Case ConsultBytes.CB_INJ_HI
                            Args.setInjector(((Args.getInjector() And &HFF) Or (CUShort(Packet(i + 2)) * &H100)))
                        Case ConsultBytes.CB_INJ_LO
                            Args.setInjector((Args.getInjector() And &HFF00) Or Packet(i + 2))
                        Case ConsultBytes.CB_LH_O2
                            Args.setO2Left(Packet(i + 2))
                        Case ConsultBytes.CB_LOAD
                            Args.setTP(Packet(i + 2))
                        Case ConsultBytes.CB_RPM_HI
                            Args.setRPM(((Args.getRPM() And &HFF) Or (CUShort(Packet(i + 2)) * &H100)))
                        Case ConsultBytes.CB_RPM_LO
                            Args.setRPM((Args.getRPM() And &HFF00) Or Packet(i + 2))
                        Case ConsultBytes.CB_SPEED
                            Args.setSpeed(Packet(i + 2))
                        Case ConsultBytes.CB_TEMP
                            Args.setTemp(Packet(i + 2))
                        Case ConsultBytes.CB_TPS
                            Args.setTps(Packet(i + 2))
                        Case ConsultBytes.CB_VETRACE
                            Args.VeTrace = Packet(i + 2)
                    End Select
                Next
            End If
        End Sub
    End Structure
    Friend Structure _typGlobalData
        Dim Consult As _typConsult
        Dim AdInputs() As _typAdInput
        Dim SwInputs() As _typSwInput
        Dim Outputs() As _typOutput
        Dim Triggers() As Byte
        Dim FlashMap As Byte
        Dim CPUTime As Single
        Sub Initialise(ByRef _Array As Byte(), ByVal Offset As Integer)
            ReDim AdInputs(AD_INPUTS_CNT - 1)
            ReDim SwInputs(SWITCH_CNT - 1)
            ReDim Outputs(OUTPUT_CNT - 1)
            Consult.Initialise(_Array, Offset)
            For i As Byte = 0 To AdInputs.Length - 1
                AdInputs(i).Initialise(_Array, Offset)
            Next
            For i As Byte = 0 To SwInputs.Length - 1
                SwInputs(i).Initialise(_Array, Offset)
            Next
            For i As Byte = 0 To Outputs.Length - 1
                Outputs(i).Initialise(_Array, Offset)
            Next
            ReDim Triggers(TRIGGER_COUNT - 1)
            Array.Copy(_Array, pp(Offset, TRIGGER_COUNT), Triggers, 0, TRIGGER_COUNT)
            FlashMap = _Array(pp(Offset))
            CPUTime = System.BitConverter.ToSingle(_Array, pp(Offset, 4))
        End Sub
        Sub ToArgs(ByRef Args As Consult_Args)
            Consult.ToArgs(Args)
            For i As Byte = 0 To Outputs.Length - 1
                Outputs(i).ToArgs(Args, i)
            Next
            For i As Byte = 0 To SwInputs.Length - 1
                SwInputs(i).ToArgs(Args, i)
            Next
            For i As Byte = 0 To AdInputs.Length - 1
                AdInputs(i).ToArgs(Args, i)
            Next
            For i As Byte = 0 To Triggers.Length - 1
                Args.setTrigger(Triggers(i), i)
            Next
            Args.CPUTime = CPUTime
        End Sub
    End Structure

    Friend Event Stream(ByVal sender As Object, ByVal e As Consult_Args)

    Sub New()
        m_consultRet = New Consult_Args
    End Sub
    Friend Sub New(ByVal Integrated As streamType)
        m_integrated = Integrated
        m_consultRet = New Consult_Args
    End Sub
    Protected Sub OnStream()
        RaiseEvent Stream(Me, m_consultRet)
    End Sub
    Friend Overloads Function Execute( _
                 ByVal backGroundWorker As System.ComponentModel.BackgroundWorker, _
                 ByVal e As System.ComponentModel.DoWorkEventArgs) As Boolean
        MyBase.Execute(backGroundWorker, e)

        Dim retValue As Boolean = True
        'BikiRom_Reset()
        '        OnStream()
        '       Exit Function
        Dim f_return As BK_return = BikiRom_Init()
        BikiRom_clear()
        If f_return = BK_return.BK_OK Or m_integrated = 3 Then
            Select Case m_integrated
                Case 0
                Case 1
                    Integrated()
                Case 3
                    consult_Test()
                Case Else
                    Integrated()
            End Select
        Else
            OnMessage(Err_Decode(f_return))
        End If
        'close_bikirom()
        ' Search for matching files.
        Return retValue
    End Function

    Private Sub consult_Test()
        While bgw.CancellationPending = False
            Threading.Thread.Sleep(100)
            m_TestThread = Now.Second
            m_consultRet = New Consult_Args()
            m_consultRet.setRPM(m_TestThread * 10)
            m_consultRet.setAFM(m_TestThread * 16)
            m_consultRet.setTemp(m_TestThread)
            m_consultRet.setMultiRegister(m_TestThread * 4)
            m_consultRet.setSpeed(m_TestThread * 3)
            m_consultRet.setTPSTrace(m_TestThread * 4)
            m_consultRet.setTps(m_TestThread * 4)
            m_consultRet.setRegister1(m_TestThread * 4)
            m_consultRet.setInjector(CInt(m_TestThread) * 10)
            m_consultRet.setIgnition(m_TestThread * 4)
            m_consultRet.setTP(m_TestThread * 4)

            m_consultRet.Status = ""
            'm_consultRet = New Consult_Args(m_TestThread * 10, 12, 11, 10, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, "")
            OnStream()
        End While
    End Sub
    Private Sub consult_Stream()
        Dim f_return(60) As Byte
        Dim f_read() As Byte
        Dim f_packet As Byte = 0
        Dim f_error As Byte
        Dim f_state As ByteRead
        Dim f_num As Integer = 0
        Dim f_cmd() As Byte = {90, 0, 90, 1, 90, 4, 90, 5, 240}
BikiRomBegin:

        BikiRom_Flush()
        BikiRom_SetTimeout(1000)
        If bgw.CancellationPending = True Or f_error >= 5 Then GoTo endSub
        If BikiRom_hexCmd("CC8100", f_return, 1) Then
            If bgw.CancellationPending = True Or f_error >= 5 Then GoTo endSub
            Debug.Print("Sent consult mode ok")
            If f_return(0) = 170 Or f_return(0) = 254 Then
                If bgw.CancellationPending = True Or f_error >= 5 Then GoTo endSub
                Debug.Print("return from consult mode OK")
consultBegin:
                If BikiRom_hexCmd("FFFFEF", f_return, 1) Then
                    If bgw.CancellationPending = True Then GoTo endSub
                    If f_return(0) = 16 Or f_return(0) = 0 Or f_return(0) = 207 Then
                        BikiRom_Flush()
                        If bgw.CancellationPending = True Or f_error >= 5 Then GoTo endSub
                        'Thread.Sleep(100)
                        Debug.Print("Send consult INIT OK")


                        BikiRom_hexCmd("5A005A015A045A05", 8)
                        BikiRom_hexCmd("5A085A105A0b5A11", 8)
                        BikiRom_hexCmd("5A0D5A135A145A15", 8)
                        BikiRom_hexCmd("5A165A0F", 5) ' 1E missing instead of 0F
                        BikiRom_hexCmd("F0")
                        ' Primary Loop
                        Do
header0:
                            If bgw.CancellationPending = True Or f_error >= 5 Or f_num >= 80 Then GoTo endSub
                            If byteInBuffer(&HFF, f_state) = ByteRead.BY_TRUE Then
                                If byteInBuffer(14, f_state) = ByteRead.BY_TRUE Then
                                    f_read = BikiRom_read(14)
                                    If f_read.Length = 14 Then
                                        m_consultRet = New Consult_Args

                                        m_consultRet.setRPM(MAKEWORD(f_read(1), f_read(0)))
                                        m_consultRet.setAFM(MAKEWORD(f_read(3), f_read(2)))
                                        m_consultRet.setTemp(f_read(4))
                                        m_consultRet.setMultiRegister(f_read(5))
                                        m_consultRet.setSpeed(f_read(6))
                                        m_consultRet.setTPSTrace(f_read(7))
                                        m_consultRet.setTps(f_read(8))
                                        m_consultRet.setRegister1(f_read(9))
                                        m_consultRet.setInjector(MAKEWORD(f_read(11), f_read(10)))
                                        m_consultRet.setIgnition(f_read(12))
                                        m_consultRet.setTP(f_read(13))

                                        m_consultRet.Status = ""
                                        f_error = 0
                                        f_num = 0
                                        OnStream()
                                    Else
                                        GoTo consultBegin
                                    End If
                                ElseIf f_state = ByteRead.BY_NODATA Then : GoTo endSub
                                Else : f_num += 1 : GoTo header0
                                End If
                            ElseIf f_state = ByteRead.BY_NODATA Then : GoTo endsub
                            Else : f_num += 1 : GoTo header0
                            End If
                            ' BikiRom_hexCmd("30", 1)
                            'f_packet = 1
                        Loop Until bgw.CancellationPending Or f_error >= 5
                        '                        BikiRom_hexCmd("5A1E5A175A105A1FF0", 6)
                    Else
                        f_error += 1
                        If bgw.CancellationPending = True Or f_error >= 5 Then GoTo endSub
                        m_status = "Consult Return From Initialization No OK"
                        OnStream()
                        GoTo BikiRomBegin
                    End If
                Else
                    'MsgBox("Error from return from consult ")
                    f_error += 1
                    If bgw.CancellationPending = True Or f_error >= 5 Then GoTo endSub
                    m_status = "Consult Initialization No OK"
                    OnStream()
                    GoTo BikiRomBegin
                End If
            Else
                'MsgBox("error getting into consult stream")
                f_error += 1
                If bgw.CancellationPending = True Or f_error >= 5 Then GoTo endSub
                m_status = "Bikirom Error - Return from Consult Mode NO Ok"
                OnStream()
                GoTo BikiRomBegin
                ' return not ok.. re-init bikirom
            End If
        Else
            'MsgBox("error getting into consult mode")
            f_error += 1
            Debug.Print("consult mode not entered")
            If bgw.CancellationPending = True Or f_error >= 5 Then GoTo endSub
            ' Sleep for 1 second then attempt to re-connect to the bikirom..
            ' return not ok.. re-init bikirom
            m_status = "Bikirom Error - Cannot enter Consult Comm's Mode"
            OnStream()
            GoTo BikiRomBegin
        End If
endSub:
    End Sub

    ''' <summary>
    ''' This sub-routine connects to the bikirom and reads the integrated consult stream
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub bikirom_Stream()
        Dim f_return(20) As Byte
        Dim f_error As Byte = 0
        Dim f_bytes As Integer = 0
        Dim f_read As Byte() = Nothing
        Dim f_state As ByteRead = ByteRead.BY_FALSE

BikiRomBegin:
        If bgw.CancellationPending = True Or f_error >= 5 Then Exit Sub
        BikiRom_Flush()
        BikiRom_SetTimeout(100)
        If bgw.CancellationPending = True Or f_error >= 5 Then GoTo endSub
        If BikiRom_hexCmd("CC1200", f_return, 1) Then
            If bgw.CancellationPending = True Or f_error >= 5 Then GoTo endSub
            Debug.Print("Sent consult mode ok")
            If f_return(0) = 170 Then
                '' Main Loop of operation
                Do
                    'Thread.Sleep(200)
                    ' BikiRom_Flush()
                    f_bytes = 0
Header:
                    If bgw.CancellationPending = True Or f_error >= 5 Or f_bytes >= 60 Then Exit Sub
                    'Debug.Print("At the header")
                    If byteInBuffer(&HDF, f_state) = ByteRead.BY_TRUE Then
                        f_bytes += 1
                        If byteInBuffer(&H55, f_state) = ByteRead.BY_TRUE Then
                            f_bytes += 1
                            If byteInBuffer(&HAA, f_state) = ByteRead.BY_TRUE Then
                                f_bytes += 1
                                '' Header Read  OK! Lets go!
                                f_read = usb_read(37)
                                'Debug.Print("At the Inside of frame")
                                If f_read.Length = 37 Then
                                    If f_read(36) = &HFF And f_read(35) = &HA5 And f_read(34) = &H5A Then
                                        m_consultRet = New Consult_Args
                                        f_bytes = 0
                                        f_error = 0
                                        'Debug.Print("Frame OK! Processing!")
                                        '' Packet Recieved A OK! WEEEEE
                                        m_consultRet.setRPM(MAKEWORD(f_read(1), f_read(0)))
                                        m_consultRet.setAFM(MAKEWORD(f_read(3), f_read(2)))
                                        m_consultRet.setTemp(f_read(4))
                                        m_consultRet.setO2Left(f_read(5))
                                        m_consultRet.setSpeed(f_read(6))
                                        m_consultRet.setBVoltage(f_read(7))
                                        m_consultRet.setTps(f_read(8))
                                        m_consultRet.setRegister1(f_read(9))
                                        m_consultRet.setInjector(MAKEWORD(f_read(11), f_read(10)))
                                        m_consultRet.setIgnition(f_read(12))
                                        m_consultRet.setRegister2(f_read(13))
                                        m_consultRet.setMAP(MAKEWORD(f_read(25), f_read(24)))
                                        m_consultRet.setAirTemp(MAKEWORD(f_read(27), f_read(26)))
                                        m_consultRet.setBKio1(f_read(28))
                                        m_consultRet.setBKio2(f_read(29))
                                        m_consultRet.setBKio3(f_read(30))
                                        m_consultRet.setBKio4(f_read(31))
                                        m_consultRet.setBk_out1(f_read(32))
                                        m_consultRet.setBk_out2(f_read(33))
                                        m_consultRet.setBk_out3(f_read(34))
                                        m_consultRet.setBk_out4(f_read(35))
                                        m_status = ""
                                        OnStream()
                                    Else
                                        f_error += 1
                                    End If
                                Else

                                End If
                            ElseIf f_state = ByteRead.BY_NODATA Then : Exit Sub
                            Else : GoTo Header
                            End If
                        ElseIf f_state = ByteRead.BY_NODATA Then : Exit Sub
                        Else : GoTo Header
                        End If
                    ElseIf f_state = ByteRead.BY_NODATA Then : Exit Sub
                    Else : GoTo Header
                    End If
                Loop Until bgw.CancellationPending = True Or f_error >= 5 Or f_bytes >= 50
            Else
                f_error += 1
                If bgw.CancellationPending = True Or f_error >= 5 Then GoTo endSub
                m_status = "Bikirom Error - Return from Consult Mode NO Ok"
                OnStream()
                Thread.Sleep(10)
                GoTo BikiRomBegin
            End If
        Else
            f_error += 1
            Debug.Print("consult mode not entered")
            If bgw.CancellationPending = True Or f_error >= 5 Then GoTo endSub
            ' Sleep for 1 second then attempt to re-connect to the bikirom..
            ' return not ok.. re-init bikirom
            m_status = "Bikirom Error - Cannot enter Consult Comm's Mode"
            OnStream()
            Thread.Sleep(10)
            GoTo BikiRomBegin
        End If
        Exit Sub
endSub:
        If f_error >= 5 Then m_status = "Error(s) in consult Stream, retrying..." Else m_status = ""
        OnStream()
    End Sub

    ''' <summary>
    ''' Integrated BikiRom New stream
    ''' </summary>
    ''' <remarks></remarks>
    Friend Sub Integrated()
        Dim f_Frame As Comm.Comm_Frame
        Dim f_Stream As Comm.Comm_Frame
        Dim f_Timeout As UInt16 = 10

retry:  Try

            f_Frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_CONSULT_INTEGRATED, , Comm.Comm_Frame.BikiFrameAction.CMD_GO)
            f_Frame.Send()

            While Not bgw.CancellationPending
                If Queue.Synchronized(m_UsbConsultIntegratedBuffer).Count = 0 Then
                    If WaitHandle.WaitAny(New WaitHandle() {m_UsbStreamEvent}, 500, False) = WaitHandle.WaitTimeout Then
                        OnMessage("Stream Timeout....")
                        If BikiRom_Init() = BK_return.BK_OK Then
                            GoTo retry
                        Else
                            Return
                        End If
                    End If
                End If

                ' Recive buffer here and do shit with it
                m_consultRet = New Consult_Args
                If Queue.Synchronized(m_UsbConsultIntegratedBuffer).Count > 0 Then
                    f_Stream = Queue.Synchronized(m_UsbConsultIntegratedBuffer).Dequeue
                    If Not IsNothing(f_Stream) Then
                        decodeStream(f_Stream, m_consultRet)
                        OnStream()
                        f_Timeout = 10
                    End If
                End If
            End While

            f_Frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_CONSULT_INTEGRATED, , Comm.Comm_Frame.BikiFrameAction.CMD_STOP)
            f_Frame.Send()

        Catch exComm As Comm_Exceptions
            If exComm.By = Comm.Comm_Frame.BikiFrameType.ID_PC And _
               exComm.Response = Comm.Comm_Frame.BikiFrameResponse.CMD_TIMEOUT Then
                f_Timeout -= 1
                If f_Timeout > 0 Then GoTo retry
            End If
            OnMessage(exComm.Description)
        Catch exUsb As USB_exceptions
            OnMessage(exUsb.Description)
        End Try
    End Sub

    Private Sub decodeStream(ByRef Stream As Comm.Comm_Frame, ByRef Args As Consult_Args)
        ' set the streams data..
        Dim f_Data(Stream.Data.Length - 12) As Byte
        Dim f_BitSet As ULong = 0
        Dim nPt As Integer = 0
        Array.Copy(Stream.Data, 7, f_Data, 0, Stream.Data.Length - 11)
        If f_Data(0) = 0 Then
            f_BitSet = CULng(f_Data(0)) << 40
            f_BitSet += CULng(f_Data(1)) << 32
            f_BitSet += CULng(f_Data(2)) << 24
            f_BitSet += CULng(f_Data(3)) << 16
            f_BitSet += CULng(f_Data(4)) << 8
            f_BitSet += CULng(f_Data(5))

            If f_BitSet > 0 AndAlso f_Data(6) = &HFF AndAlso f_Data(7) > 0 Then
                For i As UInt16 = 0 To f_Data(7)
                    Select Case decodeConsultBitSet(f_BitSet, i)
                        Case ConsultBytes.CB_AAC
                            Args.setAac(f_Data(8 + i))
                        Case ConsultBytes.CB_AFM_HI
                            Args.setAFM(((Args.getAFM() And &HFF) Or (CUShort(f_Data(8 + i)) * &H100)))
                        Case ConsultBytes.CB_AFM_LO
                            Args.setAFM((Args.getAFM() And &HFF00) Or f_Data(8 + i))
                        Case ConsultBytes.CB_BVOLT
                            Args.setBVoltage(f_Data(8 + i))
                        Case ConsultBytes.CB_DBR1
                            Args.setRegister1(f_Data(8 + i))
                        Case ConsultBytes.CB_DCR1
                            Args.setRegister2(f_Data(8 + i))
                        Case ConsultBytes.CB_DCR2
                            Args.setRegister3(f_Data(8 + i))
                        Case ConsultBytes.CB_IGN
                            Args.setIgnition(f_Data(8 + i))
                        Case ConsultBytes.CB_INJ_HI
                            Args.setInjector(((Args.getInjector() And &HFF) Or (CUShort(f_Data(8 + i)) * &H100)))
                        Case ConsultBytes.CB_INJ_LO
                            Args.setInjector((Args.getInjector() And &HFF00) Or f_Data(8 + i))
                        Case ConsultBytes.CB_LH_O2
                            Args.setO2Left(f_Data(8 + i))
                        Case ConsultBytes.CB_LOAD
                            Args.setTP(f_Data(8 + i))
                        Case ConsultBytes.CB_RPM_HI
                            Args.setRPM(((Args.getRPM() And &HFF) Or (CUShort(f_Data(8 + i)) * &H100)))
                        Case ConsultBytes.CB_RPM_LO
                            Args.setRPM((Args.getRPM() And &HFF00) Or f_Data(8 + i))
                        Case ConsultBytes.CB_SPEED
                            Args.setSpeed(f_Data(8 + i))
                        Case ConsultBytes.CB_TEMP
                            Args.setTemp(f_Data(8 + i))
                        Case ConsultBytes.CB_TPS
                            Args.setTps(f_Data(8 + i))
                        Case ConsultBytes.CB_VETRACE
                            Args.VeTrace = f_Data(8 + i)
                    End Select
                Next
            End If

            ' Bikirom Board Variable Parsing
            Args.setAD(CUShort((f_Data(24)) * &H100) Or f_Data(25), 0)
            Args.setAD(CUShort((f_Data(26)) * &H100) Or f_Data(27), 1)
            Args.setAD(CUShort((f_Data(28)) * &H100) Or f_Data(29), 2)
            Args.setSWI(f_Data(30))
            Args.setBKO(CUShort((f_Data(31)) * &H100) Or f_Data(32), 0)
            Args.setBKO(CUShort((f_Data(33)) * &H100) Or f_Data(34), 1)
            Args.setBKO(CUShort((f_Data(35)) * &H100) Or f_Data(36), 2)
            Args.setBKO(CUShort((f_Data(37)) * &H100) Or f_Data(38), 3)
            Args.setTrigger((CUInt(f_Data(39)) << 24) Or (CUInt(f_Data(40)) << 16) Or (CUInt(f_Data(41)) << 8) Or CUInt(f_Data(42)))
            Args.setDebug(New Object() {f_Data(43), f_Data(44)})
            Args.setADCLU(New Object() {System.BitConverter.ToSingle(f_Data, 51), System.BitConverter.ToSingle(f_Data, 55), System.BitConverter.ToSingle(f_Data, 59)})
            Args.FlashMap = f_Data(63)
            Args.setAUCalc(New Object() {CUShort(f_Data(64)) << 8 Or f_Data(65), CUShort(f_Data(66)) << 8 Or f_Data(67)})
            'Args.setRPM((CInt(f_Data(45)) << 8) Or f_Data(46))
            'Args.setAFM((CInt(f_Data(47)) << 8) Or f_Data(48))
            'Args.setTps(f_Data(49))
            'Args.setTemp(f_Data(50))
        ElseIf f_Data(0) >= &H15 Then
            Dim mGlobalData As New _typGlobalData
            mGlobalData.Initialise(f_Data, 1)
            mGlobalData.ToArgs(Args)
        End If

    End Sub

    ''' <summary>
    ''' Find the Consult byte in Position of the BitSet
    ''' </summary>
    ''' <param name="BitSet"></param>
    ''' <param name="Position"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Friend Shared Function decodeConsultBitSet(ByVal BitSet As UInt32, ByVal Position As Byte) As ConsultBytes
        Dim f_PosCount As UInt16 = 0
        For i As UInt16 = 0 To 32
            If (BitSet \ (2 ^ i)) And &H1 Then f_PosCount += 1
            If (f_PosCount - 1) = Position Then Return CType(i, ConsultBytes)
        Next
        Return &HFF
    End Function

    Friend Function byteInBuffer(ByVal Byt As Byte, ByRef Ret As ByteRead) As ByteRead
        Dim f_read(2) As Byte
        f_read = usb_read(1)
        If Not IsNothing(f_read) Then
            If f_read.Length >= 1 Then
                If f_read(0) = Byt Then Ret = ByteRead.BY_TRUE : Return ByteRead.BY_TRUE Else Ret = ByteRead.BY_FALSE : Return ByteRead.BY_FALSE
            Else
                Ret = ByteRead.BY_NODATA
                Return ByteRead.BY_NODATA
            End If
        Else
            Ret = ByteRead.BY_NODATA
            Return ByteRead.BY_NODATA
        End If
    End Function
End Class
